package cn.easier.activity.console.controller;

import cn.easier.activity.console.service.ActivityInfoService;
import cn.easier.activity.console.service.ActivityRuleInfoService;
import cn.easier.activity.web.entity.ActivityInfo;
import cn.easier.activity.web.entity.ActivityRule;
import cn.easier.club.base.dto.ResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 活动规则Controller
 */
@Controller
@RequestMapping("/activity/activityInfoId/{activityInfoId}/rule")
public class ActivityRuleInfoController extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(ActivityRuleInfoController.class);

    @Autowired
    ActivityInfoService activityInfoService;

    @Autowired
    ActivityRuleInfoService activityRuleInfoService;

    /**
     * 查找指定活动规则
     *
     * @return
     */
    @GetMapping
    @ResponseBody
    public ResultInfo findOne(@PathVariable Integer activityInfoId) {
        //todo 如果当前用户不存在，返回异常
        ResultInfo resultInfo = null;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
        ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
        if (activityInfo == null) {
            logger.error("获取活动规则失败，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "查找指定活动规则异常", null);
        }
        ActivityRule activityRule = activityRuleInfoService.findOneByActivityInfoId(activityInfoId);
        resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", activityRule);
        logger.info("获取指定活动规则信息：=>{}", activityRule);
        return resultInfo;
    }

    /**
     * 查找指定活动规则
     *
     * @return
     */
    @GetMapping("/findByOne")
    @ResponseBody
    public ResultInfo findByOne(@PathVariable Integer activityInfoId,@RequestParam(value = "PrizeClawType", required = true) String PrizeClawType) {
        //todo 如果当前用户不存在，返回异常
        ResultInfo resultInfo = null;
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
        ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
        if (activityInfo == null) {
            logger.error("获取活动规则失败，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "查找指定活动规则异常", null);
        }
        ActivityRule activityRule = activityRuleInfoService.findPrizeClawByActivityInfoId(activityInfoId,PrizeClawType);
        resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", activityRule);
        logger.info("获取指定活动规则信息：=>{}", activityRule);
        return resultInfo;
    }

    /**
     * 创建或编辑活动规则
     *
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultInfo saveOrUpdate(@PathVariable Integer activityInfoId, ActivityRule activityRule) {
        ResultInfo resultInfo = null;
        try {
            String user = getPrincipal().getUsername();
            String authoritiesStr = getPrincipal().getAuthoritiesStr();
            //判断添加或者更新
            if (null != activityRule.getRid()) {
                activityInfoId = activityRule.getActivityInfoId();
            } else {
                //活动规则不可重复添加
                ActivityRule createActivityRule = activityRuleInfoService.findOneByActivityInfoId(activityInfoId);
                if (null != createActivityRule) {
                    logger.error("创建或编辑活动规则异常，已经存在活动规则。user: =>{},activityInfoId:=>{}", user, activityInfoId);
                    return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建或编辑活动规则异常", null);
                }
                activityRule.setActivityInfoId(activityInfoId);
                activityRule.setCreateDate(new Date());
            }
            //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
            ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
            if (activityInfo == null) {
                logger.error("创建或编辑活动规则异常，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建或编辑活动规则异常", null);
            }
            ActivityRule returnActivityRule = activityRuleInfoService.saveAndFlush(activityRule);
            // 绑定关联
            activityInfo.setActivityRuleId(returnActivityRule.getRid());
            activityInfoService.save(activityInfo);
            logger.info("创建或编辑活动规则成功：=>{}", returnActivityRule);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", returnActivityRule);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建或编辑活动规则失败，activityInfoId：=>{}", activityInfoId);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建或编辑活动规则异常", null);
        }
        return resultInfo;
    }

    /**
     * 创建或编辑抓娃娃规则
     *
     * @return
     */
    @PostMapping("/savePrizeClaw")
    @ResponseBody
    public ResultInfo savePrizeClaw(@PathVariable Integer activityInfoId, ActivityRule activityRule) {
        ResultInfo resultInfo = null;
        try {
            String user = getPrincipal().getUsername();
            String authoritiesStr = getPrincipal().getAuthoritiesStr();
            ActivityRule createActivityRule = null;
            //查看关联的活动，如果此活动属于当前用户，根据活动编号获取指定规则。
            ActivityInfo activityInfo = getActivityInfo(authoritiesStr, user, activityInfoId);
            if (activityInfo == null) {
                logger.error("创建或编辑活动规则异常，当前用户不拥有指定活动对象。user: =>{},activityInfoId:=>{}", user, activityInfoId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建或编辑活动规则异常", null);
            }
            createActivityRule = activityRuleInfoService.findOneByPrizeClaw(activityInfoId, activityRule.getPrizeClawType());
            ActivityRule activityRule1 = this.createActivityRule(activityRule, activityInfoId);
            //判断添加或者更新
            if (null == createActivityRule) {
                // 绑定关联
                activityInfo.setActivityRuleId(activityRule1.getRid());
                activityInfoService.save(activityInfo);
            }
            logger.info("创建或编辑活动规则成功：=>{}", activityRule1);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", activityRule1);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建或编辑活动规则失败，activityInfoId：=>{}", activityInfoId);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建或编辑活动规则异常", null);
        }
        return resultInfo;
    }

    private ActivityRule createActivityRule(ActivityRule activityRule, Integer activityInfoId) {
        try {
            ActivityRule createActivityRule = activityRuleInfoService.findOneByPrizeClaw(activityInfoId, activityRule.getPrizeClawType());
            if (createActivityRule == null) {
                createActivityRule = new ActivityRule();
            }
            createActivityRule.setCreateDate(new Date());
            createActivityRule.setActivityInfoId(activityInfoId);
            createActivityRule.setIntegralParticipationTime(activityRule.getIntegralParticipationTime());
            createActivityRule.setFreeParticipationNum(activityRule.getFreeParticipationNum());
            createActivityRule.setFollow(activityRule.isFollow());
            createActivityRule.setCountNum(activityRule.getCountNum());
            createActivityRule.setConsumeIntegral(activityRule.getConsumeIntegral());
            createActivityRule.setChannelSecretkey(activityRule.getChannelSecretkey());
            createActivityRule.setChannelId(activityRule.getChannelId());
            createActivityRule.setChannelDescription(activityRule.getChannelDescription());
            createActivityRule.setMaxNum(activityRule.getMaxNum());
            createActivityRule.setShowMessage(activityRule.isShowMessage());
            createActivityRule.setSaveMessage(activityRule.isSaveMessage());
            createActivityRule.setPrizeClawType(activityRule.getPrizeClawType());
            createActivityRule.setRefresh(activityRule.isRefresh());
            createActivityRule.setLimitScore(activityRule.isLimitScore());
            createActivityRule.setPublicNumberLink(activityRule.getPublicNumberLink());
            createActivityRule.setResourceDescription(activityRule.getResourceDescription());
            createActivityRule.setResourceId(activityRule.getResourceId());
            ActivityRule activityRule1 = activityRuleInfoService.saveAndFlush(createActivityRule);
            return activityRule1;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("出错信息", e);
            return null;
        }
    }

}
